<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    #info{
        padding: 10px;
    }
</style>
<body>
<h2>聊天室</h2>
<div id="num"></div>
<div id="content"></div><br>
<input id="msg" type="text">
<input type="button" id="btn" value="发送">
<script>
    const ws = new WebSocket('ws://localhost:8080/chat');
    ws.onmessage = function (e) {

        const data = JSON.parse(e.data);
        if (typeof(data) === 'number') {
            document.getElementById("num").innerHTML = "当前在线人数："+data
        }else{
            document.getElementById("content").innerHTML +=
                "<div id='info'><div>"+data.username+"--"+data.time+"</div>"+
                "<div>"+data.message+"</div></div>"
        }

    }
    document.getElementById("btn").addEventListener("click", function () {
        let msg = document.getElementById("msg")
        ws.send(msg.value.trim());
        msg.value = "";
    })
</script>
</body>
</html>